<?php
declare(strict_types=1);

namespace App\Service\Pushapp;
use Exception;
use Hyperf\Guzzle\ClientFactory;
use Psr\Log\LoggerInterface;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Utils\ApplicationContext;
/**
 * 小米推送
 */
class XiaomiService
{
	protected ClientFactory $clientFactory;

    protected LoggerInterface $logger;

    protected $redis;

    private $send_url;

    private $base_url;

    private $appSecret;

    private $appPkgName;

    public function __construct(ClientFactory $clientFactory,LoggerFactory $loggerFactory)
    {
        $this->clientFactory = $clientFactory;
        $this->logger = $loggerFactory->get('log', 'default');
        $container = ApplicationContext::getContainer();
        $this->redis = $container->get(\Hyperf\Redis\Redis::class);
        $config = config('xhqparams.xiaomi', []);
        $this->appSecret = $config['appSecret'];
        $this->appPkgName = $config['appPkgName'];
        $this->base_url = 'https://api.xmpush.xiaomi.com/';
        $this->send_url = 'v2/message/regid';
    }
    /**
     * [sPush 推送消息]
     * @param  array  $push_data [description]
     * @param  string $reg_id    [description]
     * @return array
     */
    public function sPush(array $push_data, string $reg_id)
    {
        try {
            $sendData = [
                'restricted_package_name'=>$this->appPkgName,
                'title'=>$push_data['title'],
                'description'=>$push_data['content'],
                'notify_type'=>1,
                'registration_id'=>$reg_id,
            ];
            if (isset($push_data['extra']) && !empty($push_data['extra'])) {
                $sendData['extra.notify_foreground'] = 1;
                $sendData['extra.channel_id'] = 123089;
                $sendData['extra.PUSH_EXTRA_KEY']= json_encode($push_data['extra']);
            }
            $options = [
                'base_uri' => $this->base_url,
                'timeout'  => 3.0,
            ];
            $post_guz = [
                'headers' => ['Authorization'=>'key='.$this->appSecret],
                'form_params' => $sendData
            ];
            $resp = $this->clientFactory->create($options)->request('post', $this->send_url,$post_guz);
            $result_body = $resp->getBody()->getContents();
            $res = json_decode($result_body,true);
            
            if(!empty($res) && $res['code']=='0'){
                return ['status'=>1,'data'=>$res];
            }else{
                return ['status'=>0,'data'=>$res];
            }

        } catch (Exception $e){
            $this->logger->info($e->getMessage());
            return ['status'=>0,'data'=>$e->getMessage()];
        }
    }
}